package com.libtrace.imageselector;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

/**
 * 多图选择
 */
public class LibImageSelectorActivity extends FragmentActivity implements LibImageSelectorFragment.Callback{

    /** 最大图片选择次数，int类型，默认9 */
    public static final String EXTRA_SELECT_COUNT = "max_select_count";
    /** 图片选择模式，默认多选 */
    public static final String EXTRA_SELECT_MODE = "select_count_mode";
    /** 是否显示相机，默认显示 */
    public static final String EXTRA_SHOW_CAMERA = "show_camera";

    public static final String EXTRA_SHOW_PREVIEW = "show_preview";

    /** 选择结果，返回为 ArrayList&lt;String&gt; 图片路径集合  */
    public static final String EXTRA_RESULT = "select_result";
    /** 默认选择集 */
    public static final String EXTRA_DEFAULT_SELECTED_LIST = "default_list";
    /**
     * 状态栏标题
     * */
    public static final String EXTRA_TITLE="view_title";
    /**
     * 状态栏背景
     * */
    public static final String EXTRA_ACTIONBAR_BACKGROUND="view_actorbar_background";
    /** 选择完成按钮样式 */
    public static final String EXTRA_SELECTED_BACKGROUND="view_selected_background";
    /** 调用系统相机照片压缩到指定宽度 */
    public static final String EXTRA_CAMERA_IMAGE_WIDTH="extra_camera_image_width";
    /** 调用系统相机照片压缩到指定高度 */
    public static final String EXTRA_CAMERA_IMAGE_HEIGHT="extra_camera_image_height";

    public static final String EXTRA_CAMERA_IMAGE_QUALITY="extra_camera_image_quality";

    /** 单选 */
    public static final int MODE_SINGLE = 0;
    /** 多选 */
    public static final int MODE_MULTI = 1;

    /**
     * @param aty
     * @param resultCode
     * @param mode
     * @param showCarame
     */
    public static void startIntent(Activity aty,int resultCode,int mode,boolean showCarame){
        startIntentImel(aty,resultCode,mode,1,null,0,0,showCarame,false,480,640,80);
    }

    /**
     * @param aty
     * @param resultCode
     * @param mode
     * @param showCarame
     * @param showPriview
     */
    public static void startIntent(Activity aty,int resultCode,int mode,boolean showCarame,boolean showPriview){
        startIntentImel(aty,resultCode,mode,1,null,0,0,showCarame,showPriview,480,640,80);
    }

    /**
     * @param aty
     * @param resultCode
     * @param mode
     * @param cameraImageWidth
     * @param cameraImageHeight
     * @param quality
     */
    public static void startIntent(Activity aty,int resultCode,int mode,int cameraImageWidth,int cameraImageHeight,int quality){
        startIntentImel(aty,resultCode,mode,1,null,0,0,true,false,cameraImageWidth,cameraImageHeight,quality);
    }

    /**
     * @param aty
     * @param resultCode
     * @param mode
     * @param selectCount
     * @param title
     * @param actionbarBackground
     * @param btn_select_background
     * @param showPriview
     * @param cameraImageWidth
     * @param cameraImageHeight
     * @param quality
     */
    public static void startIntent(Activity aty,int resultCode,int mode,int selectCount,String title,int actionbarBackground
            ,int btn_select_background,boolean showPriview,int cameraImageWidth,int cameraImageHeight,int quality){
        startIntentImel(aty,resultCode,mode,selectCount,title,actionbarBackground,btn_select_background,true,showPriview,cameraImageWidth,cameraImageHeight,quality);
    }

    /**
     * @param aty
     * @param resultCode 启动activity返回状态吗
     * @param mode 照片选择模式
     * @param title 标题
     * @param actionbarBackground 标题栏背景
     * @param btn_select_background 选择完成按钮背景
     * @param showCarame 是否显示相机
     * @param showPriview 是否显示预览相册
     * @param cameraImageWidth 调用系统相机照片压缩宽度
     * @param cameraImageHeight 调用系统相机照片压缩高度
     * @param quality 调用系统相机照片压缩质量
     */
    static void startIntentImel(Activity aty,int resultCode,int mode,int selectCount,String title,int actionbarBackground,int btn_select_background,
                                boolean showCarame,boolean showPriview,int cameraImageWidth, int cameraImageHeight,int quality){
        Intent _mIm = new Intent(aty,LibImageSelectorActivity.class);
        _mIm.putExtra(EXTRA_SELECT_MODE,mode);
        if(mode==MODE_MULTI){
            _mIm.putExtra(EXTRA_SELECT_MODE,selectCount);
        }
        _mIm.putExtra(EXTRA_TITLE,title);
        _mIm.putExtra(EXTRA_ACTIONBAR_BACKGROUND,actionbarBackground);
        _mIm.putExtra(EXTRA_SELECTED_BACKGROUND,btn_select_background);

        _mIm.putExtra(EXTRA_SHOW_CAMERA,showCarame);
        _mIm.putExtra(EXTRA_SHOW_PREVIEW,showPriview);
        _mIm.putExtra(EXTRA_CAMERA_IMAGE_WIDTH,cameraImageWidth);
        _mIm.putExtra(EXTRA_CAMERA_IMAGE_HEIGHT,cameraImageHeight);
        _mIm.putExtra(EXTRA_CAMERA_IMAGE_QUALITY,quality);

        aty.startActivityForResult(_mIm,resultCode);
    }


    private ArrayList<String> resultList = new ArrayList<>();

    private Button mSubmitButton;

    private int mDefaultCount;

    private int mCameraImageWidth  = 480;

    private int mCameraImageHeight = 640;

    private int mCameraImageQuality = 80;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.lib_image_activity_default);

        if(!ImageLoader.getInstance().isInited()){
            ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(this));
        }
        Intent intent = getIntent();
        mDefaultCount = intent.getIntExtra(EXTRA_SELECT_COUNT, 9);
        int mode = intent.getIntExtra(EXTRA_SELECT_MODE, MODE_MULTI);
        boolean isShow = intent.getBooleanExtra(EXTRA_SHOW_CAMERA, true);
        boolean isPreview = intent.getBooleanExtra(EXTRA_SHOW_PREVIEW,false);
        mCameraImageWidth = intent.getIntExtra(EXTRA_CAMERA_IMAGE_WIDTH,480);
        mCameraImageHeight = intent.getIntExtra(EXTRA_CAMERA_IMAGE_HEIGHT,640);
        mCameraImageQuality = intent.getIntExtra(EXTRA_CAMERA_IMAGE_QUALITY,80);
        String _title = intent.getStringExtra(EXTRA_TITLE);


        if(mode == MODE_MULTI && intent.hasExtra(EXTRA_DEFAULT_SELECTED_LIST)) {
            resultList = intent.getStringArrayListExtra(EXTRA_DEFAULT_SELECTED_LIST);
        }

        Bundle bundle = new Bundle();
        bundle.putInt(LibImageSelectorFragment.EXTRA_SELECT_COUNT, mDefaultCount);
        bundle.putInt(LibImageSelectorFragment.EXTRA_SELECT_MODE, mode);
        bundle.putBoolean(LibImageSelectorFragment.EXTRA_SHOW_CAMERA, isShow);
        bundle.putBoolean(LibImageSelectorFragment.EXTRA_SHOW_PREVIEW, isPreview);
        bundle.putStringArrayList(LibImageSelectorFragment.EXTRA_DEFAULT_SELECTED_LIST, resultList);

        getSupportFragmentManager().beginTransaction()
                .add(R.id.image_grid, Fragment.instantiate(this, LibImageSelectorFragment.class.getName(), bundle))
                .commit();

        // 返回按钮
        findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setResult(RESULT_CANCELED);
                finish();
            }
        });

        TextView  mTitle = (TextView) findViewById(R.id.lib_image_btn_title);

        // 完成按钮
        mSubmitButton = (Button) findViewById(R.id.commit);
        if(resultList == null || resultList.size()<=0){
            mSubmitButton.setText("完成");
            mSubmitButton.setEnabled(false);
        }else{
            mSubmitButton.setText("完成("+resultList.size()+"/"+mDefaultCount+")");
            mSubmitButton.setEnabled(true);
        }
        mSubmitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(resultList != null && resultList.size() >0){
                    // 返回已选择的图片数据
                    Intent data = new Intent();
                    data.putStringArrayListExtra(EXTRA_RESULT, resultList);
                    setResult(RESULT_OK, data);
                    finish();
                }
            }
        });
        if(_title!=null){
            mTitle.setText(_title);
        }
        mTitle.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    public void onSingleImageSelected(String path) {
        Intent data = new Intent();
        resultList.add(path);
        data.putStringArrayListExtra(EXTRA_RESULT, resultList);
        setResult(RESULT_OK, data);
        finish();
    }

    @Override
    public void onImageSelected(String path) {
        if(!resultList.contains(path)) {
            resultList.add(path);
        }
        // 有图片之后，改变按钮状态
        if(resultList.size() > 0){
            mSubmitButton.setText("完成("+resultList.size()+"/"+mDefaultCount+")");
            if(!mSubmitButton.isEnabled()){
                mSubmitButton.setEnabled(true);
            }
        }
    }

    @Override
    public void onImageUnselected(String path) {
        if(resultList.contains(path)){
            resultList.remove(path);
            mSubmitButton.setText("完成("+resultList.size()+"/"+mDefaultCount+")");
        }else{
            mSubmitButton.setText("完成("+resultList.size()+"/"+mDefaultCount+")");
        }
        // 当为选择图片时候的状态
        if(resultList.size() == 0){
            mSubmitButton.setText("完成");
            mSubmitButton.setEnabled(false);
        }
    }

    @Override
    public void onCameraShot(File imageFile) {
        if(imageFile != null) {
            //
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            Bitmap $bitmap = BitmapFactory.decodeFile(imageFile.toString(),options);

            // 计算缩放比例，由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
            final int height = options.outHeight;
            final int width = options.outWidth;
            float scale = calculateInSampleSize(options, mCameraImageWidth, mCameraImageHeight);
            // 因为结果为int型，如果相除后值为0.n，则最终结果将是0

            if (scale <= 0) {
                scale = 1;
            }

            options.inSampleSize = (int) scale;
            options.inJustDecodeBounds = false;
            $bitmap = BitmapFactory.decodeFile(imageFile.toString(),options);
            try {
                imageFile.delete();
                try {
                    imageFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    FileOutputStream out = new FileOutputStream(imageFile);
                    if ($bitmap.compress(Bitmap.CompressFormat.JPEG, mCameraImageQuality, out)) {
                        out.flush();
                        out.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if ($bitmap != null) {
                    $bitmap.recycle();
                    $bitmap = null;
                }
            }catch (Exception e){

            }catch (Error e){

            }
            //
            Intent data = new Intent();
            resultList.add(imageFile.getAbsolutePath());
            data.putStringArrayListExtra(EXTRA_RESULT, resultList);
            setResult(RESULT_OK, data);
            finish();
        }
    }
    private static int calculateInSampleSize(BitmapFactory.Options options,
                                            int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float) height / (float) reqHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) reqWidth);
            }
        }
        return inSampleSize;
    }
}
